<template>
  <div>
    <input type="file" id="upload" accept="image/jpg" @change="upload" />
    <img :src="img" id="show" width="200" />
  </div>
</template>

<script>
const ws = new WebSocket("ws://192.168.1.8:8000");
export default {
  data() {
    return {
      uploadUrl: "http://192.168.1.8:7001/api/img",
      img: "",
    };
  },
  mounted() {
    ws.addEventListener("open", this.handlerOpen.bind(this), false);
    ws.addEventListener("close", this.handlerClose.bind(this), false);
    ws.addEventListener("error", this.handlerError.bind(this), false);
    ws.addEventListener("message", this.handlerMessage.bind(this), false);
  },
  methods: {
    upload(e) {
      const formData = new FormData();
      formData.append("file", e.target.files[0]);
      this.uploadImg(formData);
    },
    uploadImg(formData) {
      this.$axios({
        url: this.uploadUrl,
        method: "post",
        data: formData,
        processData: false,
        contentType: false,
      }).then((res) => {
        this.img = res.data.url;
        this.handlerSendMsg(res.data.url);
      });
    },
    handlerSendMsg(imgUrl) {
      ws.send(imgUrl);
    },
    handlerOpen(e) {
      console.log("Open");
    },
    handlerClose(e) {
      console.log("Close");
    },
    handlerError(e) {
      console.log("Error");
    },
  },
};
</script>

<style></style>
